<?php

namespace  Api\Controller;
use Com\Easemob;
use User\Api\UserApi;
class HxController extends ApiController{
    protected $hx = '';
    public function __construct(){
        parent::__construct();
        $hx=new Easemob();
        $this->hx = $hx;
        /** 测试不判断登录 modify by zhang 2016 end **/
    }
    /**
    * 新增单个用户
    * @param string $username
    */
   public function createUser($username, $password) {
       empty($username) &&  response(-2,'','用户名不能为空');
       $result=$this->hx->createUser($username, $password);
       return $result;
   }
   /**
    *获取单个用户  Todo  暂无地方使用，若使用需要修改
    */
   public function getUser() {
       $uid = I('uid');//用户id
       $username = M('member')->where('uid='.$uid)->getField('nickname');
       $result = $this->hx->getUser($username);
       return $result;
   }

    /**
     *删除单个用户  Todo  暂无地方使用，若使用需要修改
     */
    public function deleteUser() {
        $uid = I('uid');//用户id
        $username = M('member')->where('uid='.$uid)->getField('nickname');
        $result = $this->hx->deleteUser($username);
        return $result;
    }

    /**
     *重置用户密码
     */
    public function resetPassword($username, $newpassword){
        $result = $this->hx->resetPassword($username, $newpassword);
        return $result;
    }

    /**
     * 编辑用户名称
     */
    public function editNickname($username, $nickname) {
        $result = $this->hx->editNickname($username, $nickname);
        return $result;
    }
    /**
     * 搜索用户
     */
    public function findFriend() {
        $p = I('p');
        $result = M('member')->where("nickname like '%".$p."%' or zd_id='".$p."'")->select();
        foreach ($result as $key=>$val) {
            $username = M('ucenter_member')->where('id='.$val['uid'])->getField('username');
            $result[$key]['username'] = $username;
            $result[$key]['headimg'] = M('picture')->where('id='.$val['avatar'])->getField('path');
            $result[$key]['state'] = $this->isOnline($username);
        }
        $result?response(1, $result):response(-9);
    }

    /**
     * 判断是不是好友
     */
    public function isFriend(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);

        $uid = API_UID;
        $fid = I('id');
        $where['uid'] = $uid;
        $where['fid'] = $fid;
        $is_exist = M('user_friend')->where($where)->find();

        if ($is_exist) {
            response(-1, '', '该用户已经是您的好友');
        }else{
            response(1, '', '可以添加好友');
        }

    }

    /**
     * 添加好友
     */
    public function addFriend() {
        $username= I('username');
        $f_zd_id = I('f_zd_id');
        $friend = M('ucenter_member')->where("id='".$f_zd_id."'")->find();
        $fid = $friend['id'];
        $friend_name = M('ucenter_member')->where('id='.$fid)->getField('username');
        $uid = M('ucenter_member')->where("username='".$username."'")->getField('id');

        if ($fid == $uid) {
            response(-2, '', '您不能添加自己为好友');
        }

        if (!$fid) {
            response(-3, '', '该用户不存在');
        }
        $where['uid'] = $uid;
        $where['fid'] = $fid;
        $is_exist = M('user_friend')->where($where)->find();
        if ($is_exist) {
            response(-1, '', '该用户已经是您的好友');
        }
        //获取该人的默认分组
        $where= array('uid'=>$uid, 'name'=>'战友');
        $group_id = M('user_group')->where($where)->getField('id');
        $data = array(
            'uid'=>$uid,
            'fid'=>$fid,
            'update_time'=>NOW_TIME,
            'group_id'=>$group_id
        );
        $resultdata = M('user_friend')->add($data);
        $group_id1 = M('user_group')->where(array('uid'=>$fid, 'name'=>'战友'))->getField('id');
        $data1 = array(
            'uid'=>$fid,
            'fid'=>$uid,
            'update_time'=>NOW_TIME,
            'group_id'=>$group_id1
        );
        $resultdata1 = M('user_friend')->add($data1);
        $result = $this->hx->addFriend($username, $friend_name);
        !isset($result['error'])&& $resultdata && $resultdata1?response(1):response(-9);
    }

    /**
     * 添加分组
     */
    public function addGroup() {
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        $uid = API_UID;
        $data = array(
            'name' => I('name'),
            'uid' => $uid
        );
        $is_exist = M('user_group')->where("name='".$data['name']."' and uid='".$uid."'")->find();
        if ($is_exist) {
            response(-2, '', '该分组已存在');
        }
        $result = M('user_group')->add($data);
        $result ? response(1):response(-9);
    }
    /**
     * 获取分组名称
     */
    public function getFriendGroup() {
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        $uid = API_UID;
        $result = M('user_group')->where('uid='.$uid)->select();
        $result ? response(1,$result):response(-9);
    }
    /**
     * 修改分组名称
     */
    public function renameFriendGroup() {
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        $rename = I('rename');//原名称
        $name = I('name');//新名称
        $uid = API_UID;
        $is_exist = M('user_group')->where("name='".$name."' and uid='".$uid."'")->find();
        if ($is_exist) {
            response(-2, '', '该分组已存在');
        }
        $result = M('user_group')->where("name='".$rename."' and uid='".$uid."'")->save(array('name'=>$name));
        $result?response(1):response(-9);
    }
    /**
     * 删除分组
     */
    public function deleteFriendGroup() {
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        $uid = API_UID;
        $id = I('id');//分组id
        $result = M('user_group')->where('id='.$id)->delete();
        if ($result) {
            $where['uid'] = array('eq', $uid);
            $where['group_id'] = array('eq', $id);
            $friends = M('user_friend')->where($where)->select();
            foreach ($friends as $key=>$val) {
                M('user_friend')->where($where)->save(array('group_id'=>0));
            }
            response(1);
        } else {
            response(-9);
        }
    }
    /**
     * 好友置顶
     */
    public function friendTop() {
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        $friend_name = I('friend_name');
        $fid = M('ucenter_member')->where("username='".$friend_name."'")->getField('id');
        $uid = API_UID;
        $result = M('user_friend')->where('uid='.$uid.' && fid='.$fid)->setField(array('is_top'=>1, 'update_time'=>NOW_TIME));
        $result ? response(1):response(-9);
    }
    /**
     * 移除置顶
     */
    public function removeFriendTop() {
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        $friend_name = I('friend_name');
        $fid = M('ucenter_member')->where("username='".$friend_name."'")->getField('id');
        $uid = API_UID;
        $result = M('user_friend')->where('uid='.$uid.' && fid='.$fid)->setField(array('is_top'=>0, 'update_time'=>NOW_TIME));
        $result ? response(1):response(-9);
    }
    /**
     * 将好友拉到分组--仅支持加入单个好友  Todo不完善
     */
    public function friendAddGroup() {
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        $friend_name = I('friend_name');
        $gourpid = I('group_id');//分组id
        $fid = M('ucenter_member')->where("username='".$friend_name."'")->getField('id');//好友id
        $uid = API_UID;
        $where = array(
            'uid'=>$uid,
            'fid'=>$fid
        );
        $result = M('user_friend')->where($where)->setField('group_id', $gourpid);
        $result ? response(1):response(-9);
    }

    /**
     * 删除好友(双向删除)
     */
    public function deleteFriend() {
        $username = I('username');
        $friend_name = I('friend_name');
        $fid = M('ucenter_member')->where("username='".$friend_name."'")->getField('id');
        $uid = M('ucenter_member')->where("username='".$username."'")->getField('id');
        //从环信中删除好友
        $result = $this->hx->deleteFriend($username, $friend_name);
        //从本地删除好友关系
        $where = array('uid'=>$uid, 'fid'=>$fid);
        $result1 = M('user_friend')->where($where)->delete();
        $where1 = array('uid'=>$fid, 'fid'=>$uid);
        $result2 = M('user_friend')->where($where1)->delete();
        !isset($result['error']) && $result1 && $result2? response(1):response(-9);
    }

    /**
     * 获取好友列表  isOnline  Todo  考虑分组和置顶
     */
    public function showFriends() {
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        $uid = API_UID;
        //获取该好友的所有分组
        $getGroup = M('user_group')->where('uid='.$uid)->select();
        $result = array();
        foreach($getGroup as $key=>$val) {
            $result[$key]['groupName'] = $val['name'];
            //获取该分组下的所有好友
            $where['uid'] = array('eq', $uid);
            $where['group_id'] = array('eq', $val['id']);
            $members = M('user_friend') ->where($where)->select();
            foreach($members as $key1=>$val1) {
                $member = M('member')->where('uid='.$val1['fid'])->find();
                $val1['nick'] = $member['nickname'];
                $val1['username'] = M('ucenter_member')->where('id='.$val1['fid'])->getField('username');
                $val1['headimg'] = M('picture')->where('id='.$member['avatar'])->getField('path');
                $val1['state'] = $this->isOnline($val1['username']);
                $result[$key]['users'][$key1] = $val1;
            }
        }
        $result?response(1, $result):response(-9);
    }

    /**
     * 查看好友
     * 名称，战斗号，地区，性别，个人签名，头像
     */
    public function checkFriend() {
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        $uid = API_UID;
        $friend_name = I('friend_name');
        $result = M('member')->alias('m')
            ->join('left join jzb_ucenter_member u on m.uid=u.id')
            ->field('m.nickname,m.zd_id,m.district,m.sex,m.sign,m.avatar,u.username,m.uid')
            ->where("u.username='".$friend_name."'")->find();
        if ($result) {
            $result['headimg'] = M('picture')->where('id='.$result['avatar'])->getField('path');
            $is_friend = M('user_friend')->where(array('uid'=>$uid, 'fid'=>$result['uid']))->find();
            if ($is_friend) {
                $result['is_friend'] = 'true';
            } else {
                $result['is_friend'] = 'false';
            }
            response(1,$result);
        } else {
            response(-9);
        }
    }
    /**
     * 好友投诉
     */
    public function friendComplaint() {
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        $data = array(
            'content' => I('content'),//聊天内容
            'uid' => API_UID,//谁投诉的
            'toid' => I('toid'),//投诉谁
            'create_time' => NOW_TIME,
            'type'=>I('type')//投诉类型
        );
        $result = M('user_complaint')->add($data);
        $result && response(1, $result) && response(-9);
    }
    /*
     查看用户黑名单
     */
    function getBlacklist(){
        $username = I('username');
        $result = $this->hx->getBlacklist($username);
        isset($result['error'])?response(-9):response(1,$result);
    }
    /*
     往黑名单中加人
     */
    function addUserForBlacklist(){
        $username = I('username');
        $friend_name = I('friend_name');
        $result = $this->hx->addUserForBlacklist($username, $friend_name);
        isset($result['error'])?response(-9):response(1,$result);
    }
    /*
     从黑名单中减人
     */
    function deleteUserFromBlacklist(){
        $username = I('username');
        $friend_name = I('friend_name');
        $result = $this->hx->deleteUserFromBlacklist($username, $friend_name);
        isset($result['error'])?response(-9):response(1,$result);
    }
    /*
     查看用户是否在线
    */
    function isOnline($paramName=''){
        $usernameNew = !empty($paramName)?$paramName:I('username');
        $result = $this->hx->isOnline($usernameNew);
        if (empty($paramName)) {
            isset($result['error'])?response(-9):response(1,$result['data'][$usernameNew]);
        } else {
            return $result['data'][$paramName];
        }
    }
    /*
    查看用户离线消息数
    */
    function getOfflineMessages(){
        $username = I('username');
        $result = $this->hx->getOfflineMessages($username);
        isset($result['error'])?response(-9):response(1,$result);
    }
    /*
    查看某条消息的离线状态
    ----deliverd 表示此用户的该条离线消息已经收到
    */
    function getOfflineMessageStatus(){
        $username = I('usename');
        $msg_id = I('msg_id');
        $result = $this->hx->getOfflineMessageStatus($username,$msg_id);
        isset($result['error'])?response(-9):response(1,$result);
    }
    /*
     禁用用户账号
     */
    function deactiveUser(){
        $username = I('username');
        $result = $this->hx->deactiveUser($username);
        isset($result['error'])?response(-9):response(1,$result);
    }
    /*
     解禁用户账号
     */
    function activeUser(){
        $username = I('username');
        $result = $this->hx->activeUser($username);
        isset($result['error'])?response(-9):response(1,$result);
    }
    /*
     强制用户下线
     */
    function disconnectUser(){
        $username = I('username');
        $result = $this->hx->disconnectUser($username);
        isset($result['error'])?response(-9):response(1,$result);
    }
    /*
     获取app中的所有群组----不分页
     */
    function getGroups(){
        $limit = I('limit');
        $result = $this->hx->getGroups($limit);
        isset($result['error'])?response(-9):response(1,$result);
    }
    /*
     获取app中的所有群组---分页
    */
    function getGroupsForPage(){
        $limit = I('limit');
        $getGroups = $this->getGroups();
        $cursor = $getGroups['cursor'];
        $result = $this->hx->getGroupsForPage($limit, $cursor);
        isset($result['error'])?response(-9):response(1,$result);
    }
    /**
     * 群投诉
     */
    public function groupComplaint() {
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        $data = array(
            'content' => I('content'),//聊天内容
            'uid' => API_UID,//谁投诉的
            'group_id' => I('group_id'),//投诉群
            'create_time' => NOW_TIME,
            'type'=>I('type')//投诉类型
        );
        $result = M('group_complaint')->add($data);
        $result && response(1, $result) && response(-9);
    }
    /**
     * 群置顶
     */
    public function groupTop() {
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        $where['id'] = I('group_id');
        $where['uid'] = API_UID;
        $result = M('group')->where($where)->save(array('is_top'=>1));
        $result?response(1):response(-9);
    }
    /**
     * 移除群置顶
     */
    public function removeGroupTop() {
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        $where['id'] = I('group_id');
        $where['uid'] = API_UID;
        $result = M('group')->where($where)->save(array('is_top'=>0));
        $result?response(1):response(-9);
    }
    /**
     * 获取该用户的群列表
     */
    public function getUserGroup() {
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        $uid = API_UID;
        $username = M('ucenter_member')->where('id='.$uid)->getField('username');
        $list = M('group_member')->alias('m')
            ->join('left join jzb_group g on g.id=m.gid')
            ->where("username='".$username."'")
            ->field('g.cover_id,g.id,g.name,g.is_top')
            ->order('g.is_top desc,g.update_time desc')->select();
        foreach ($list as $key=>$val) {
            $list[$key]['imgPath'] = M('picture')->where('id='.$val['cover_id'])->getField('path');
            $list[$key]['countMember'] = M('group_member')->where('gid='.$val['id'])->count();
        }
        $list ? response(1, $list) : response(-9);
    }
    /*
     获取一个或多个群组的详情
     */
    function getGroupDetail($groupids=''){
        $group_ids = empty($groupids)?I('group_ids'):$groupids;//多个群组用逗号分隔
        $g_ids=strpos($group_ids,',')?implode(',',$group_ids):$group_ids;
        $result = $this->hx->getGroupDetail($g_ids);
        if (empty($groupids)) {
            isset($result['error'])?response(-9):response(1,$result);
        } else {
            return $result;
        }
    }
    /**
     * 判断是否已经建过一个群
     */
    public function hasGroup() {
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        $uid = API_UID;
        $is_exist = M('group')->where('uid='.$uid)->count();
       // $is_exist = M('group')->field('count(id)')->where('uid='.$uid)->find();
        if ($is_exist >= 2) {
            $data['is_exist'] = 1;
        } else {
            $data['is_exist'] = 0;
        }
        response(1, $data);
    }
    /*
    创建一个群组
     */
    function createGroup(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        $uid = API_UID;
        /* 判断团号是否存在 modify by liujb 20170209 start */
        $rand = I('rand')?I('rand'):$this->rand();
        $grpres = M('group')->where(array('number'=>'ZDT'.$rand))->find();
        if($grpres){
            response(-8, $grpres, '团号已存在');
        }
        /* 判断团号是否存在 modify by liujb 20170209 end */
        //获取该用户下的群组
        $num = M('group')->where('uid='.$uid)->count();
        if ($num>=2) {
            $amount = M('member')->where('uid='.$uid)->getField('amount');
            if (!$amount) {
                $amount = 0;
            }
            if ($amount<100) {
                response(-2, '', '余额不足',$amount);
            }
            M('member')->where('uid='.$uid)->setDec('amount', '100');
            /* 添加资金流水记录 modify by liujb 20170208 start */
            addCapitalflow('购买团号','-100',$uid);
            /* 添加资金流水记录 modify by liujb 20170208 end */
        }
        $username = M('ucenter_member')->where('id='.$uid)->getField('username');
        $members = I('members');
        if (empty($members)) {
            $members = [];
        }
        $options = array(
            "groupname" => I('groupname'), //群组名称，此属性为必须的
            "desc" => I('desc'), //群组描述，此属性为必须的
            "public" => boolval(I('public')), //是否是公开群，此属性为必须的true or false
            "maxusers" => intval(I('maxusers')), //群组成员最大数（包括群主），值为数值类型，默认值200，最大值2000，此属性为可选的
            "approval" => boolval(I('approval')), //加入公开群是否需要批准，默认值是false（加入公开群不需要群主批准），此属性为必选的，私有群必须为true
            "owner" => $username, //群组的管理员，此属性为必须的
            "members" => $members //群组成员，此属性为可选的，但是如果加了此项，数组元素至少一个（注：群主jma1不需要写入到members里面）["admin123"]
        );
        $result = $this->hx->createGroup($options);
        $group_id = $result['data']['groupid'];
        if (!isset($result['error'])) {

            if (I('rand')) {
                $amount = M('member')->where('uid='.$uid)->getField('amount');
                if (!$amount) {
                    $amount = 0;
                }
                if ($amount<100) {
                    response(-2, '', '余额不足');
                }
                M('member')->where('uid='.$uid)->setDec('amount', '100');
                /* 添加资金流水记录 modify by liujb 20170208 start */
                addCapitalflow('购买团号','-100',$uid);
                /* 添加资金流水记录 modify by liujb 20170208 end */
            }
            $data = array(
                'name'=>I('groupname'),
                'uid'=>$uid,
                'id'=>$group_id,
                'update_time'=>NOW_TIME,
                'cover_id' =>I('cover_id'),
                'number'=>'ZDT'.$rand
            );
            $res = M('group')->add($data);
            if ($res>0) {
                //为群组添加成员
                array_push($members, $username);
                foreach ($members as $key=>$val) {
                    $dataMem['username'] = $val;
                    $dataMem['gid'] = $group_id;
                    $dataMem['is_manager'] = (($val == $username)?1:0);
                    M('group_member')->add($dataMem);
                }
                response(1,$result);
            } else {
                $this->deleteGroup($result['data']['groupid']);
                response(-2, '', '创建失败，请重新创建');
            }
        } else {
            response(-9);
        }
    }
    public function rand() {
        $rand = rand(10000, 99999);
        $is_exist = M('randnumber')->where('number='.$rand)->find();
        if ($is_exist) {
            $this->rand();
        } else {
            M('randnumber')->add(array('number'=>$rand));
            return $rand;
        }
    }
    /**
     * 生成五个自选号码
     */
    public function getNumber() {
        for($i=1;$i<6;$i++) {
            $result[] = $this->rand();
        }
        response(1, $result);
    }
    /**
     * 选取自选号码收费
     */
    public function getMoney() {
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        $uid = API_UID;
        $amount = M('member')->where('uid='.$uid)->getField('amount');
        if (!$amount) {
            $amount = 0;
        }
        if ($amount<100) {
            response(-2, '', '余额不足');
        }
        M('member')->where('uid='.$uid)->setDec('amount', '100');
        /* 添加资金流水记录 modify by liujb 20170208 start */
        addCapitalflow('购买团号','-100',$uid);
        /* 添加资金流水记录 modify by liujb 20170208 end */
        response(1);
    }
    /*
     * 获取团名和群聊名
     */
    public function getTeamname() {
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        $uid = API_UID;
        $groupid = I('groupid');
        $username = M('ucenter_member')->where('id='.$uid)->getField('username');
        $result['groupname'] = M('group')->where('id='.$groupid)->getField('name');
        $result['nickname'] = M('member')->where('uid='.$uid)->getField('nickname');

        $where['username'] = $username;
        $where['gid'] = $groupid;
        $result['rename'] = M('group_member')->where($where)->getField('rename');
        $gid = M('group_member')->where($where)->getField('groupid');
        $result['bumenname'] = M('group_group')->where('id='.$gid)->getField('name');
        response(1, $result);
    }
    /*
     修改群组信息
     */
    function modifyGroupInfo($group_id='', $name=''){
        $group_id = !empty($group_id)?$group_id:I('group_id');
        //获取群组名称
        $groupInfo = $this->getGroupDetail($group_id);
        $groupname = empty($name)?I('groupname'):$groupInfo['data']['name'];
        $options = array(
            "groupname" => $groupname, //群组名称，修改时值不能包含斜杠（"/"）。有空格时需要用“+”代替。
            "description" => I('description'), //群组描述，修改时值不能包含斜杠（"/"）。有空格时需要用“+”代替。
            "maxusers" => I('maxusers') //群组成员最大数（包括群主），值为数值类型
        );
        $result = $this->hx->modifyGroupInfo($group_id, $options);
        if (!isset($result['error'])) {
            $data = array(
                'name'=>I('groupname'),
                'update_time'=>NOW_TIME,
                'cover_id'=>I('cover_id')
            );
            $res = M('group')->where('id='.$group_id)->save($data);
            if ($res) {
                response(1,$result);
            } else {
                $this->modifyGroupInfo($group_id, 222);
                response(-2, '', '修改失败');
            }
        } else {
            response(-9);
        }
    }
    /*
     删除群组
     */
    function deleteGroup($group_id=''){
        $result = $this->hx->deleteGroup($group_id);
        if (!isset($result['error'])) {
            $res = M('group')->where('id='.$group_id)->delete();
            M('group_group')->where('gid='.$group_id)->delete();
            M('group_member')->where('gid='.$group_id)->delete();
            if ($res) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
    /**
     * 群成员退出群组
     */
    public function  leaveGroup() {
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        $uid = API_UID;
        $group_id = I('group_id');
        $info = M('group')->where('id='.$group_id)->find();
        if ($info['uid'] == $uid) {
            $result = $this->deleteGroup($group_id);
        } else {
            //获取用户名
            $username = M('ucenter_member')->where('id='.$uid)->getField('username');
            $where['username'] = $username;
            $where['gid'] = $group_id;
            $result = M('group_member')->where($where)->delete();
        }
        if ($result) {
            response(1);
        } else {
            response(-9);
        }
    }
    /*
     获取群组中的成员  Todo
     */
    function getGroupUsers(){
        $group_id = I('group_id');
        $members = M('group_member')->where('gid='.$group_id)->select();
        foreach ($members as $key=>$val) {
            $uid = M('ucenter_member')->where("username='".$val['username']."'")->getField('id');
            $info = M('member')->where("uid=".$uid)->find();
            if ($members[$key]['rename'] != "") {
                $members[$key]['nickname'] = $members[$key]['rename'];
            } else {
                $members[$key]['nickname'] = $info['nickname'];
            }

            $headimg = M('picture')->where('id='.$info['avatar'])->getField('path');
            $members[$key]['headimg'] = $headimg?$headimg:'';
            $members[$key]['isOnline'] = $this->isOnline($val['username']);
        }
        $members?response(1,$members):response(-9);
    }
    /*
     群组单个加人
     */
    function addGroupMember(){
        $group_id = I('group_id');
        $username = I('username');
        //获取团队信息
        $groupInfo = M('group')->where('id='.$group_id)->getField('self');
        if ($groupInfo == 1) {
            //判断是否已经加入到自带团队
            $where['g.self'] = 1;
            $where['m.username'] = $username;
            $num = M('group')->alias('g')
                ->join('left join jzb_group_member m on g.id=m.gid')
                ->where($where)
                ->count();
            if ($num>1) {
                response(-2, '','您已加入过自带军团');
            }
            $self=1;
        }  else {
            $self = 0;
        }
        $result = $this->hx->addGroupMember($group_id, $username);
        if (!isset($result['error'])) {
            $where['gid'] = array('eq', $group_id);
            $where['username'] = array('eq',$username);
            $is_exist = M('group_member')->where($where)->find();
            if ($is_exist) {
                response(-2, '', '添加失败，该成员已存在');
            }
            $res = M('group_member')->add(array('gid'=>$group_id, 'username'=>$username, 'self'=>$self));
            $res?response(1,$result):response(-9);
        } else {
            response(-9);
        }
    }
    /*
     群组批量加人
     */
    function addGroupMembers(){
        $group_id = I('group_id');
        $usernames = I('usernames');//多个username用逗号隔开
        $usernames = explode(',', $usernames);
        //获取团队信息
        $groupInfo = M('group')->where('id='.$group_id)->getField('self');
        if ($groupInfo == 1) {
            foreach($usernames as $key=>$val) {
                //判断是否已经加入到自带团队
                $where['g.self'] = 1;
                $where['m.username'] = $val;
                $num = M('group')->alias('g')
                    ->join('left join jzb_group_member m on g.id=m.gid')
                    ->where($where)
                    ->count();
                if ($num>1) {
                    continue;
                }
            }
            $self = 1;
        } else {
            $self = 0;
        }
        $user['usernames'] = $usernames;
        $result = $this->hx->addGroupMembers($group_id, $user);
        if (!isset($result['error'])){
            foreach ($user['usernames'] as $key=>$val) {
                $where['gid'] = array('eq', $group_id);
                $where['username'] = array('eq',$val);
                $res = M('group_member')->where($where)->find();
                if ($res) continue;
                M('group_member')->add(array('gid'=>$group_id, 'username'=>$val, 'self'=>$self));
            }
            response(response(1,$result));
        } else {
            response(-9);
        }
    }
    /*
     群组单个减人
     */
    function deleteGroupMember(){
        $group_id = I('group_id');
        $username = I('username');
        $result = $this->hx->deleteGroupMember($group_id, $username);
        if (!isset($result['error'])) {
            $where['gid'] = array('eq', $group_id);
            $where['username'] = array('eq',$username);
            $res = M('group_member')->where($where)->delete();
            $res?response(1,$result):response(-9);
        } else {
            response(-9);
        }
    }
    /*
     群组批量减人
     */
    function deleteGroupMembers(){
        $group_id = I('group_id');
        $usernames = I('usernames');// 多个用户名用逗号隔开
        $numbers = explode(',', $usernames);
        $result = $this->hx->deleteGroupMembers($group_id, $usernames);
        if (!isset($result['error'])){
            foreach ($numbers as $key=>$val) {
                $where['gid'] = array('eq', $group_id);
                $where['username'] = array('eq',$val);
                M('group_member')->where($where)->delete();
            }
            response(response(1,$result));
        } else {
            response(-9);
        }
    }
    /*
    获取一个用户参与的所有群组
    */
    function getGroupsForUser(){
        $username = I('username');
        $result = $this->hx->getGroupsForUser($username);
        isset($result['error'])?response(-9):response(1,$result);
    }
    /*
     群组转让
     */
    function changeGroupOwner(){
        $group_id = I('group_id');
        $newname = I('newname');
        $options = array('newowner'=>$newname);//array('newowner'=>'新用户名称');
        $uid = M('ucenter_member')->where("username='".$newname."'")->getField('id');
        if (!$uid) {
            response(-2, '', '该用户不存在无法转让');
        }
        $result = $this->hx->changeGroupOwner($group_id,$options);
        if (!isset($result['error'])) {
            $res = M('group')->where('id='.$group_id)->save(array('uid'=>$uid));
            M('group_member')->where('gid='.$group_id)->save(array('is_manager'=>0));
            M('group_member')->where(array('gid'=>$group_id, 'username'=>$newname))->save(array('is_manager'=>1));
            $res?response(1, $result):response(-9);
        } else {
            response(-9);
        }
    }
    /**
     * 修改群名片
     */
    public function rename(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        $uid = API_UID;
        $rename = I('rename');
        $where['gid'] = I('groupid');
        $where['username'] = M('ucenter_member')->where('id='.$uid)->getField('username');
        $result = M('group_member')->where($where)->setField('rename', $rename);
        $result?response(1):response(-9);
    }
    /**
     * 添加群分组
     */
    public function addGroupType() {
        $data['name'] = I('name');
        $data['gid'] = I('group_id');
        $where['name'] =$data['name'];
        $where['gid'] = $data['gid'];
        $is_exist = M('group_group')->where($where)->find();
        if ($is_exist) response(-2, '', '该分组已存在');
        $result = M('group_group')->add($data);
        $result?response(1):response(-9);
    }
    /**
     * 删除分组
     */
    public function deleteGroupType() {
        $group_id = I('group_id');//群id
        $name = I('name');
        //获取分组id
        $groupid = M('group_group')->where("name='".$name."'")->getField('id');
        $where1 = array('gid'=>$group_id, 'name'=>$name);
        $result = M('group_group')->where($where1)->delete();
        if ($result) {
            $members = M('group_member')->where('gid='.$group_id.' && groupid='.$groupid)->select();
            foreach ($members as $key=>$val) {
                $where['username'] = array('eq', $val['username']);
                $where['gid'] = $group_id;
                M('group_member')->where($where)->save(array('groupid'=>0));
            }
            response(1);
        } else {
            response(-9);
        }
    }

    /**
     * 获取群分组
     */
    function getGroupTypeList(){
        $gid = I('gid');//群id
        $where['gid'] =$gid;
        $result = M('group_group')->where($where)->select();
        $result?response(1,$result):response(-9);
}

    /**
     * 是否是管理员
     */
    function  isManager(){
        $gid = I('gid');//群id
        $username = I('username');
        $where['gid'] = $gid;
        $where['username'] = $username;
        $result = M('group_member')->where($where)->getField('is_manager');
        $result?response(1,$result):response(-9);
    }

    /**
     * 群分组添加人员
     */
    function addGroupTypeMember(){
        $groupid = I('groupid');//分组id
        $username = I('username');
        $gid = I('gid');//群id
        $where['gid'] = array('eq', $gid);
        $where['username'] = array('eq',$username);
        $is_exist = M('group_member')->where($where)->find();
        $is_user = M('ucenter_member')->where("username='".$username."'")->find();
        if (!$is_user) response(-1, '', '该用户不存在');
        if ($is_exist) {
            if ($is_exist['groupid'] != 0) {
                M('group_member')->where($where)->delete();
               // response(-2, '', '添加失败，该成员已存在');
            } else {
                $res = M('group_member')->where($where)->save(array('groupid'=>$groupid));
                response(1, $res);
            }
        }
        $res = M('group_member')->add(array('groupid'=>$groupid, 'username'=>$username, 'gid'=>$gid));
        $res?response(1,$res):response(-9);
    }

    /**
     * 群分组批量加人
     */
    function addGroupTypeMembers(){
        $groupid = I('groupid');//分组id
        $usernames = I('usernames');//多个手机号用逗号隔开
        $usernames = explode(',', $usernames);
        $gid = I('gid');//群id
        foreach ($usernames as $key=>$val) {
            $where['gid'] = array('eq', $gid);
            $where['username'] = array('eq',$val);
            $is_exist = M('group_member')->where($where)->find();
            if ($is_exist) {
                M('group_member')->where($where)->save(array('groupid'=>$groupid));
            } else {
                $res=M('group_member')->add(array('gid'=>$gid, 'username'=>$val, 'groupid'=>$groupid));
            }
        }
        $res?response(1):response(-9);
    }

    /**
     * 为群分组删除人员
     */
    function deleteGroupTypeMember(){
        $groupid = I('groupid');
        $username = I('username');
        $where['groupid'] = array('eq', $groupid);
        $where['username'] = array('eq',$username);
        $res = M('group_member')->where($where)->save(array('groupid'=>0));
        $res?response(1):response(-9);
    }

    /**
     * 群分组批量删人
     */
    function deleteGroupTypeMembers(){
        $groupid = I('groupid');
        $usernames = I('usernames');// 多个用户名用逗号隔开
        $numbers = explode(',', $usernames);
        foreach ($numbers as $key=>$val) {
            $where['groupid'] = array('eq', $groupid);
            $where['username'] = array('eq',$val);
            $res = M('group_member')->where($where)->save(array('groupid'=>0));
        }
        $res?response(1):response(-9);
    }
    /**
     * 获取分组成员
     */
    public function getGroupMember(){
        $groupid = I('groupid');//分组id
        $gid     =  I('gid');   //群id
        $where['groupid'] = $groupid;
        $where['gid']      = $gid;
        $result = M('group_member')->where($where)->select();
        if($result){
            foreach ($result as &$re) {
                $uid =  M('ucenter_member')->where('username=' . $re['username'])->getField('id');
                $avatar = M('member')->where('uid=' . $uid)->getField('avatar');
                $re['avatar_path'] = get_url($avatar);
            }
        }
        $result?response(1, $result):response(-9);
    }

    /**
     * 获取群成员
     */
    public function getQunMeber(){
        $gid = I('gid');//分组id
        $result = M('group_member')->where('gid='.$gid)->select();
        $result?response(1, $result):response(-9);
    }

    /**
     *获取我的部门
     */
    function getMyGroup(){
        $gid = I('gid');//分组id
        $username= I('username');
        $where['gid'] =  $gid;
        $where['username'] = $username;
        $mygroup = M('group_member')->where($where)->getField('groupid');
        $grouplist = M('group_group')->where('gid='.$gid)->select();
        $data['mygroupid'] = $mygroup;
        $data['grouplist'] = $grouplist;
        if($grouplist){
            response(1, $data);
        }else{
            response(-9);
        }
    }


    /**
     * 查找群
     */
    public function findGroup() {
        $p = I('p');//select * from jzb_group where name like '%test%' or id='test'
        $result = M('group')->where("name like '%".$p."%' or id ='".$p."'")->select();
        foreach($result as $key=>$val) {
            $result[$key]['headimg'] = M('picture')->where('id='.$val['cover_id'])->getField('path');
        }
        $result?response(1, $result):response(-9);
    }
    /*
     查询一个群组黑名单用户名列表
     */
    function getGroupBlackList(){
        $group_id = I('group_id');
        $result = $this->hx->getGroupBlackList($group_id);
        isset($result['error'])?response(-9):response(1,$result);
    }
    /*
     群组黑名单单个加人
     */
    function addGroupBlackMember(){
        $group_id = I('group_id');
        $username = I('username');
        $result = $this->hx->addGroupBlackMember($group_id, $username);
        isset($result['error'])?response(-9):response(1,$result);
    }
    /*
     群组黑名单批量加人
     */
    function addGroupBlackMembers(){
        $group_id = I('group_id');
        $usernames = I('usernames');//array('usernames'=>array('name1','name2'...))
        $result = $this->hx->addGroupBlackMembers($group_id, $usernames);
        isset($result['error'])?response(-9):response(1,$result);
    }
    /*
     群组黑名单单个减人
     */
    function deleteGroupBlackMember(){
        $group_id = I('group_id');
        $username = I('username');
        $result = $this->hx->deleteGroupBlackMember($group_id, $username);
        isset($result['error'])?response(-9):response(1,$result);
    }
    /*
     群组黑名单批量减人
     */
    function deleteGroupBlackMembers(){
        $group_id = I('group_id');
        $usernames = I('usernames');//多个用户名用逗号隔开
        $result = $this->hx->deleteGroupBlackMembers($group_id, $usernames);
        isset($result['error'])?response(-9):response(1,$result);
    }
    /**
     * 修改群组名称
     */
    public function reGroupName() {
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        $uid = API_UID;
        $name = I('name');
        $where['id'] = I('groupid');
        //判断是否是群主
        $info = M('group')->where($where)->find();
        if ($info['uid'] == $uid) {
            $result = M('group')->where($where)->setField('name', $name);
            $result?response(1):response(-9);
        } else {
            response(-2, '', '您没有权限修改群组名称');
        }
    }



    /*
     创建聊天室
     */
    function createChatRoom(){
        $owner = I('owner');
        $options = array(
            "name" => I('name'), //聊天室名称，此属性为必须的
            "description" => I('description'), //聊天室描述，此属性为必须的
            "maxusers" => I('maxusers'), //聊天室成员最大数（包括群主），值为数值类型，默认值200，最大值5000，此属性为可选的
            "owner" => $owner, //聊天室的管理员，此属性为必须的
            "members" =>  I('members')//聊天室成员，此属性为可选的，但是如果加了此项，数组元素至少一个（注：群主jma1不需要写入到members里面）
        );
        $result = $this->hx->createChatRoom($options);
        isset($result['error'])?response(-9):response(1,$result);
    }
    /*
     修改聊天室信息
     */
    function modifyChatRoom(){
        $chatroom_id = I('chatroom_id');
        $options = array(
            "name" => I('name'), //聊天室名称，修改时值不能包含斜杠("/")。有空格时需要用“+”代替。
            "description" => I('description'), //聊天室描述，修改时值不能包含斜杠("/")。有空格时需要用“+”代替。
            "maxusers" => I('maxusers'), //聊天室成员最大数（包括群主），值为数值类型
        );
        $result = $this->hx->modifyChatRoom($chatroom_id, $options);
        isset($result['error'])?response(-9):response(1,$result);
    }
    /*
     删除聊天室
     */
    function deleteChatRoom(){
        $chatroom_id = I('chatroom_id');
        $result = $this->hx->deleteChatRoom($chatroom_id);
        isset($result['error'])?response(-9):response(1,$result);
    }
    /*
     获取app中所有的聊天室
     */
    function getChatRooms(){
        $result = $this->hx->getChatRooms();
        isset($result['error'])?response(-9):response(1,$result);
    }

    /*
     获取一个聊天室的详情
     */
    function getChatRoomDetail(){
        $chatroom_id = I('chatroom_id');
        $result = $this->hx->getChatRoomDetail($chatroom_id);
        isset($result['error'])?response(-9):response(1,$result);
    }
    /*
     获取一个用户加入的所有聊天室
     */
    function getChatRoomJoined(){
        $username = I('username');
        $result = $this->hx->getChatRoomJoined($username);
        isset($result['error'])?response(-9):response(1,$result);
    }
    /*
     聊天室单个成员添加
     */
    function addChatRoomMember(){
        $chatroom_id = I('chatroom_id');
        $username = I('username');
        $result = $this->hx->addChatRoomMember($chatroom_id, $username);
        isset($result['error'])?response(-9):response(1);
    }
    /*
     聊天室批量成员添加
     */
    function addChatRoomMembers(){
        $chatroom_id = I('chatroom_id');
        $usernames = I('usernames');//array('usernames'=>array('name1','name2'...))
       // $usernames = array('13240094303','13240094304');
        $result = $this->hx->addChatRoomMembers($chatroom_id, $usernames);
        isset($result['error'])?response(-9):response(1,$result);
    }
    /*
     聊天室单个成员删除
     */
    function deleteChatRoomMember(){
        $chatroom_id = I('chatroom_id');
        $username = I('username');
        $result = $this->hx->deleteChatRoomMember($chatroom_id, $username);
        isset($result['error'])?response(-9):response(1,$result);
    }
    /*
     聊天室批量成员删除
     */
    function deleteChatRoomMembers(){
        $chatroom_id = I('chatroom_id');
        $usernames = I('usernames');//多个用户名之间用逗号隔开
        $result = $this->hx->deleteChatRoomMembers($chatroom_id, $usernames);
        isset($result['error'])?response(-9):response(1,$result);
    }


}